<!-- 广告管理 -->
<template>
	<div class="app-container">
		<div v-if="showBlock">
			<!-- 搜索 -->
      <div class="filter-container tw-filter">
        <el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-edit" v-has="$store.state.user.btn_common+'add'" @click="handleAdd()">添加</el-button>
        <el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-delete" v-has="$store.state.user.btn_common+'del'" @click="handleDelete()">批量删除</el-button>

        <el-select v-model="queryList.ident" class="filter-item tw-filter-input" placeholder="请选择位置" clearable>
        	<el-option v-for="item in advIdentListAll" :key="item.key" filter="false" :label="item.value" :value="item.key"></el-option>
        </el-select>
        <!-- <el-input v-model="queryList.company_id" placeholder="请输入企业ID" class="filter-item tw-filter-input" clearable/> -->
        <el-select v-model="queryList.state" class="filter-item tw-filter-input" placeholder="请选择状态" clearable>
        	<el-option key="" label="全部状态" value="" />
        	<el-option key="1" label="启用" value="1" />
        	<el-option key="0" label="禁用" value="0" />
        </el-select>

        <el-button v-waves class="filter-item tw-filter-button" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      </div>

			<!-- 表格内容展示 -->
      <el-table
        ref="multipleTable"
        :key="tableKey"
        v-loading="listLoading"
        :data="tableList"
        @selection-change="handleSelectionChange"
        border fit highlight-current-row style="width: 100%;">
				<el-table-column type="selection" width="50" />
				<el-table-column label="排序" prop="sort_id" align="center" width="80" v-has="$store.state.user.btn_common+'edit'">
					<template slot-scope="{row}">
						<el-input v-model="row.sort_id" class="edit-input" size="small" @change="updateSort(row.id,row.sort_id)" />
					</template>
				</el-table-column>
        <el-table-column label="位置名称" align="left" width="400">
        	<template slot-scope="{row}">{{row.ident_name}}【{{row.ident}}】</template>
        </el-table-column>
				<el-table-column label="图片尺寸（px）" align="left">
					<template slot-scope="{row}">{{row.width}} * {{row.height}}</template>
				</el-table-column>
				<el-table-column label="广告数量" align="center">
					<template slot-scope="{row}">
						<span v-if="row.num">{{row.num}}</span>
						<span v-else>不限</span>
					</template>
				</el-table-column>
        <!-- <el-table-column label="所属企业" align="left">
        	<template slot-scope="{row}">
        		<span v-if="row.company_id">{{row.company_name}}【{{row.company_id}}】</span>
        	</template>
        </el-table-column> -->
				<el-table-column label="状态" align="center">
					<template slot-scope="{row}">
						<span v-if="row.state == 1">启用</span>
						<span v-else>禁用</span>
					</template>
				</el-table-column>

				<el-table-column label="操作" width="300px" align="center" class-name="small-padding fixed-width">
					<template slot-scope="{row}">
						<el-button size="mini" v-has="$store.state.user.btn_common+'list_item'" @click="handleItemShow(row.id)">管理广告</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'edit'" @click="handleEdit(row.id)">编辑</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'upshow'" v-if="row.state" @click="handleUpshow(row.id)">禁用</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'show'" v-else @click="handleShow(row.id)">启用</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'del'" @click="handleDelete(row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="isPage && listTotal > 0" :total="listTotal" :page.sync="queryList.curpage" :limit.sync="queryList.page" @pagination="getList" />

			<!-- 添加/编辑 -->
			<el-dialog width="40%" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
			  <el-form label-position="right" label-width="120px" ref="dataForm" :rules="rules" :model="form">
					<el-form-item label="广告位置" prop="ident">
						<el-select v-model="form.ident" class="filter-item" placeholder="请选择广告位置" style="display:block;">
							<el-option v-for="item in advIdentList" :key="item.key" filter="false" :label="item.value" :value="item.key"></el-option>
						</el-select>
            <p class="tw-tip-text">广告显示的位置</p>
					</el-form-item>
					<el-form-item label="宽度(px)" prop="width" filter="false">
						<el-input v-model="form.width" placeholder="请输入宽度" />
						<p class="tw-tip-text">整数</p>
					</el-form-item>
					<el-form-item label="高度(px)" prop="height" filter="false">
						<el-input v-model="form.height" placeholder="请输入高度" />
						<p class="tw-tip-text">整数</p>
					</el-form-item>
					<el-form-item label="广告数量" prop="num" filter="false">
						<el-input v-model="form.num" placeholder="请输入广告数量" />
            <p class="tw-tip-text">整数 0表示不限</p>
					</el-form-item>
          <el-form-item label="状态" prop="state">
          	<el-radio-group v-model="form.state">
          		<el-radio :label="1">启用</el-radio>
          		<el-radio :label="0">禁用</el-radio>
          	</el-radio-group>
          </el-form-item>
					<el-form-item label="排序" prop="sort_id">
						<el-input v-model="form.sort_id" placeholder="请输入排序" filter="false" />
					</el-form-item>
				</el-form>

				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogStatus==='create'?createData():updateData()">保存</el-button>
					<el-button @click="dialogFormVisible = false">取消</el-button>
				</div>
			</el-dialog>
		</div>

		<!-- 广告管理 -->
		<div v-if="showBlock1">
			<!-- 过滤器容器 -->
			<div class="filter-container tw-filter">
				<el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-arrow-left" @click="handleReturn()">返回</el-button>
				<el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-edit"v-has="$store.state.user.btn_common+'add_item'" @click="handleAdd1()">添加</el-button>
				<el-button class="filter-item tw-filter-button" size="medium" icon="el-icon-delete" v-has="$store.state.user.btn_common+'del_item'" @click="handleDelete1()">批量删除</el-button>

				<el-input v-model="queryList1.title" placeholder="广告标题" class="filter-item tw-filter-input" />
				<el-select v-model="queryList1.state" class="filter-item tw-filter-input" placeholder="请选择状态" clearable>
					<el-option key="" label="全部状态" value="" />
					<el-option key="1" label="启用" value="1" />
					<el-option key="0" label="禁用" value="0" />
				</el-select>

				<el-button v-waves class="filter-item tw-filter-button" size="medium" icon="el-icon-search" @click="handleFilter1">搜索</el-button>
			</div>

			<!-- 表格内容展示 -->
			<el-table
        ref="multipleTable"
        :key="tableKey1"
        v-loading="listLoading1"
        :data="tableList1"
        border fit highlight-current-row style="width: 100%;"
        @selection-change="handleSelectionChange1"
      >
				<el-table-column type="selection" width="50" />
				<el-table-column label="排序" prop="sort_id" align="center" width="80" v-has="$store.state.user.btn_common+'edit_item'">
					<template slot-scope="{row}">
						<el-input v-model="row.sort_id" class="edit-input" size="small" @change="updateSort1(row.id,row.sort_id)" />
					</template>
				</el-table-column>
				<el-table-column label="广告标题" prop="title" align="left" />
				<!-- <el-table-column label="类型" align="center">
					<template slot-scope="{row}">
						<span v-if="row.type == 0">图片</span>
						<span v-if="row.type == 1">视频</span>
					</template>
				</el-table-column> -->
				<el-table-column label="图片" prop="image_src_str" align="center">
					<template slot-scope="{row}">
						<el-image style="height: 50px" fit="cover" v-if="row.image_src_str" :src="row.image_src_str" :preview-src-list="[row.image_src_str]"></el-image>
					</template>
				</el-table-column>
				<!-- <el-table-column label="视频链接" prop="video_src_str" align="left"></el-table-column> -->
				<el-table-column label="跳转链接" prop="url" align="left"></el-table-column>
				<el-table-column label="状态" align="center">
					<template slot-scope="{row}">
						<span v-if="row.state == 1">启用</span>
						<span v-else>禁用</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" width="220" align="center" class-name="small-padding fixed-width">
					<template slot-scope="{row}">
						<el-button size="mini" v-has="$store.state.user.btn_common+'edit_item'" @click="handleEdit1(row.id)">编辑</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'upshow_item'" v-if="row.state" @click="handleUpshow1(row.id)">禁用</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'show_item'" v-else @click="handleShow1(row.id)">启用</el-button>
						<el-button size="mini" v-has="$store.state.user.btn_common+'del_item'" @click="handleDelete1(row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<pagination v-show="isPage1 && listTotal1 > queryList1.page" :total="listTotal1" :page.sync="queryList1.curpage" :limit.sync="queryList1.page" @pagination="getItemList" />

			<!-- 添加/编辑 -->
			<el-dialog width="40%" :title="textMap1[dialogStatus1]" :visible.sync="dialogFormVisible1">
			  <el-form label-position="right" label-width="120px" ref="dataForm1" :rules="rules1" :model="form1">
					<el-form-item label="广告标题" prop="title" filter="false">
						<el-input v-model="form1.title" placeholder="请输入广告标题" />
					</el-form-item>
			    <el-form-item label="广告图" prop="image_src">
			      <UploadOne v-on:uploadCallBack="uploadCallBack($event, 'image_src')" :showUrl="form1.image_src_str" :formData="{dir_type: apiPath1}" tip="支持格式gif,jpg,png"></UploadOne>
			    </el-form-item>
          <el-form-item label="跳转链接" prop="url">
          	<el-input v-model="form1.url" placeholder="请输入跳转链接" />
          </el-form-item>
          <el-form-item label="状态" prop="state">
          	<el-radio-group v-model="form1.state">
          		<el-radio :label="1">启用</el-radio>
          		<el-radio :label="0">禁用</el-radio>
          	</el-radio-group>
          </el-form-item>
          <el-form-item label="排序" prop="sort_id">
          	<el-input v-model="form1.sort_id" placeholder="请输入排序" filter="false" />
          </el-form-item>
        </el-form>

				<div slot="footer" class="dialog-footer">
					<el-button @click="dialogStatus1==='create'?createData1():updateData1()">保存</el-button>
					<el-button @click="dialogFormVisible1 = false">取消</el-button>
				</div>
			</el-dialog>
		</div>
	</div>
</template>

<script>
	import Pagination from '@/components/Pagination' // 基于el分页的二次封装
	import waves from '@/directive/waves' // waves directive
	import UploadOne from '@/components/Upload/UploadOne'

	export default {
		components: { Pagination,UploadOne },
		directives: { waves },
		data() {
			return {
				// 数据列表
				listLoading: true,
				tableKey: 0,
				listTotal: 0,
				isPage: false,
				tableList: [],
				multipleSelection: [],//多选数据
				// 添加/编辑弹窗
				dialogFormVisible: false,
				dialogStatus: '',
				textMap: {
					update: '编辑',
					create: '添加'
				},
        //键字段
        keyName: 'id',
        apiPath: 'project.advposition',

				// 搜索数据
				queryList: {
					page: this.$store.state.settings.page, // 每页显示数量
					curpage: 1, // 当前页码
					ident: '', // 广告位置ID
          //company_id: '',
					state: null //状态：0-禁用 1-启用
				},

				// 表单数据
				form: {
					id: 0, //ID
					ident: '', // 广告位置ID
					width: '', //宽度（px）
					height: '', //高度（px）
					num: 0, //广告数量
					state: 1, //状态：0-禁用 1-启用
					sort_id: 255 // 排序
				},
				// 重置数据
				formReset: {
					id: 0, //ID
					ident: '', // 广告位置ID
					width: '', //宽度（px）
					height: '', //高度（px）
					num: 0, //广告数量
					state: 1, //状态：0-禁用 1-启用
					sort_id: 255 // 排序
				},
				// 验证
				rules: {
					ident: [{ required: true, message: '请选择广告位置！', trigger: 'change' }]
				},
				//广告位置标识列表
				advIdentListAll: [],
				advIdentList: [],


        //广告管理
        showBlock: true,
        showBlock1: false,
        relevanceID: 'ap_id', //关联ID
				ap_id: '', //父表ID

        /*广告*/
        // 数据列表
        listLoading1: true,
        tableKey1: 1,
        listTotal1: 0,
        isPage1: false,
        tableList1: [],
        multipleSelection1: [],//多选数据
        // 添加/编辑弹窗
        dialogFormVisible1: false,
        dialogStatus1: '',
        textMap1: {
        	update: '编辑',
        	create: '添加'
        },
        //键字段
        keyName1: 'id',
        apiPath1: 'project.adv',

        // 搜索数据
        queryList1: {
        	page: this.$store.state.settings.page, // 每页显示数量
        	curpage: 1, // 当前页码
          ap_id: 0,
        	title: '', //广告标题
        	state: null, //状态：0-禁用 1-启用
        },

        // 表单数据
        form1: {
          id: '',
        	ap_id: '', // 广告位置ID
        	title: '', //广告标题
					type: '', //广告类型
        	image_src: '', //图片url
          image_src_str: '',
					video_src: '', //视频链接
        	url: '', // 跳转链接
        	state: 1, //状态：0-禁用 1-启用
        	sort_id: 255, // 排序
        },
        // 重置数据
        formReset1: {
          id: '',
        	ap_id: '', // 广告位置ID
        	title: '', //广告标题
					type: '', //广告类型
        	image_src: '', //图片url
          image_src_str: '',
					video_src: '', //视频链接
        	url: '', // 跳转链接
        	state: 1, //状态：0-禁用 1-启用
        	sort_id: 255, // 排序
        },
        // 验证
        rules1: {
        	title: [{ required: true, message: '请输入广告标题！', trigger: 'change' }],
        	image_src: [{ required: true, message: '请上传广告图片！', trigger: 'change' }],
        },
			}
		},
		created() {
			//获取广告位-列表
			this.getList()
			//获取广告位-标识-列表
			this.getAdvIdentList()
		},

		methods: {
			//获取广告位-标识-列表
			getAdvIdentList() {
        this.$api.fetchListDictionary({ident: 'adv_ident'}).then(response => {
					this.advIdentList = JSON.parse(JSON.stringify(response.list))
					response.list.unshift({
						key: '0',
						value: '全部位置'
					});
					this.advIdentListAll = response.list
				})
			},
/*******************************公共方法******************************/
      // 搜索
      handleFilter() {
      	this.queryList.curpage = 1
      	this.tableList = []
        this.listTotal = 0
      	this.getList()
      },
      // 列表选择
      handleSelectionChange(val) {
      	this.multipleSelection = val
      },
      // 重置form
      resetForm() {
      	this.form = JSON.parse(JSON.stringify(this.formReset))
      },
			// 获取数据列表
			getList() {
				this.listLoading = true
				this.$api.fetchList(this.queryList, this.apiPath).then(response => {
					this.tableList = response.list
					this.listTotal = response.list_count
					this.isPage = response.is_page
          this.listLoading = false
				})
			},
			// 添加
			handleAdd() {
			  this.resetForm()
			  this.dialogStatus = 'create'
			  this.dialogFormVisible = true
			  this.$nextTick(() => {
			    this.$refs['dataForm'].clearValidate()
			  })
			},
			// 编辑
			handleEdit(id = 0) {
			  this.resetForm()
			  // 获取详情
			  this.$api.getDetail({ id: id }, this.apiPath).then(response => {

          	//response.detail.ident = parseInt(response.detail.ident);
          //数据处理
          for(let key in this.form){
            if(response.detail.hasOwnProperty(key)){
              this.form[key] = response.detail[key]
            }
          }
			  })
			  this.dialogStatus = 'update'
			  this.dialogFormVisible = true
			  this.$nextTick(() => {
			    this.$refs['dataForm'].clearValidate();
			  })
			},
      // 添加-数据提交
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$api.add(this.form, this.apiPath).then(() => {
              // 重新获取列表
              this.queryList.curpage = 1
              this.tableList = []
              this.getList()

              this.dialogFormVisible = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 编辑-数据提交
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$api.edit(this.form, this.apiPath).then(response => {
              // 重新获取列表
              this.getList()

              this.dialogFormVisible = false
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 删除
      handleDelete(id = 0) {
        let current = this
        let id_str = ''
        if (!id) {
          // 多选
          if (!this.multipleSelection.length) {
            this.$message({
              message: '请选择删除的条目！',
              type: 'warning'
            })
            return false
          }
          // 数据处理
          this.multipleSelection.forEach(item => {
            id_str += item[current.keyName] + ','
          })
        } else {
          id_str = id
        }

        // 提交数据
        this.$confirm('确认删除数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.del({ id_str: id_str }, this.apiPath).then(response => {
            // 重新获取列表
            this.getList()
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          })
        })
      },
			// 排序
			updateSort(id = 0, sort = '') {
				this.$api.editSort({
					id: id,
					sort: sort
				}, this.apiPath).then(response => {
					this.$message({
						message: '排序成功',
						type: 'success'
					})
				})
			},
			//启用
			handleShow(id = 0) {
				this.$confirm('确认启用数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$api.show({ id_str: id }, this.apiPath).then(response => {
						// 重新获取列表
						this.getList()
						this.$message({
							message: '启用成功',
							type: 'success'
						})
					})
				})
			},
			//禁用
			handleUpshow(id = 0) {
				this.$confirm('确认禁用数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$api.upshow({ id_str: id }, this.apiPath).then(response => {
						// 重新获取列表
						this.getList()
						this.$message({
							message: '禁用成功',
							type: 'success'
						})
					})
				})
			},
/*******************************公共方法END******************************/

			/*管理广告*/
      //点击管理广告
      handleItemShow(id=0) {
        this.queryList1[this.relevanceID] = id;
        this[this.relevanceID] = id;
        this.showBlock = false;
        this.showBlock1 = true;
        //获取广告列表
        this.getItemList();
      },
      //点击返回广告位
      handleReturn() {
        this[this.relevanceID] = 0;
        this.queryList1[this.relevanceID] = 0;
        this.showBlock = true;
        this.showBlock1 = false;
      },
      // 图片上传回调
      uploadCallBack(res, fieldName=''){
        if(fieldName){
          this.form1[fieldName] = res.fileName;
          this.form1[fieldName+'_str'] = res.showUrl;
        }else{
          this.$message('图片字段错误！');
        }
      },
/*******************************公共方法1******************************/
      // 搜索
      handleFilter1() {
      	this.queryList1.curpage = 1
      	this.tableList1 = []
        this.listTotal1 = 0
      	this.getItemList()
      },
      // 列表选择
      handleSelectionChange1(val) {
      	this.multipleSelection1 = val
      },
      // 重置form
      resetForm1() {
      	this.form1 = JSON.parse(JSON.stringify(this.formReset1))
      },
			// 获取数据列表
			getItemList() {
				this.listLoading1 = true
				this.$api.fetchList(this.queryList1, this.apiPath1).then(response => {
					this.tableList1 = response.list
					this.listTotal1 = response.list_count
					this.isPage1 = response.is_page
          this.listLoading1 = false
				})
			},
			// 添加
			handleAdd1() {
			  this.resetForm1()
			  this.dialogStatus1 = 'create'
			  this.dialogFormVisible1 = true
			  this.$nextTick(() => {
			    this.$refs['dataForm1'].clearValidate()
			  })
			},
			// 编辑
			handleEdit1(id = 0) {
			  this.resetForm1()
			  // 获取详情
			  this.$api.getDetail({ id: id }, this.apiPath1).then(response => {
          //数据处理
          for(let key in this.form1){
            if(response.detail.hasOwnProperty(key)){
              this.form1[key] = response.detail[key]
            }
          }
			  })
			  this.dialogStatus1 = 'update'
			  this.dialogFormVisible1 = true
			  this.$nextTick(() => {
			    this.$refs['dataForm1'].clearValidate();
			  })
			},
      // 添加-数据提交
      createData1() {
        this.$refs['dataForm1'].validate((valid) => {
          if (valid) {
            this.form1[this.relevanceID] = this[this.relevanceID]
            this.$api.add(this.form1, this.apiPath1).then(() => {
              // 重新获取列表
              this.queryList1.curpage = 1
              this.tableList1 = []
              this.getItemList()

              this.dialogFormVisible1 = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 编辑-数据提交
      updateData1() {
        this.$refs['dataForm1'].validate((valid) => {
          if (valid) {
            this.form1[this.relevanceID] = this[this.relevanceID]
            this.$api.edit(this.form1, this.apiPath1).then(response => {
              // 重新获取列表
              this.getItemList()

              this.dialogFormVisible1 = false
              this.$message({
                message: '编辑成功',
                type: 'success'
              })
            })
          }
        })
      },
      // 删除
      handleDelete1(id = 0) {
        let current = this
        let id_str = ''
        if (!id) {
          // 多选
          if (!this.multipleSelection1.length) {
            this.$message({
              message: '请选择删除的条目！',
              type: 'warning'
            })
            return false
          }
          // 数据处理
          this.multipleSelection1.forEach(item => {
            id_str += item[current.keyName1] + ','
          })
        } else {
          id_str = id
        }

        // 提交数据
        this.$confirm('确认删除数据吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.del({ id_str: id_str }, this.apiPath1).then(response => {
            // 重新获取列表
            this.getItemList()
            this.$message({
              message: '删除成功',
              type: 'success'
            })
          })
        })
      },
			// 排序
			updateSort1(id = 0, sort = '') {
				this.$api.editSort({
					id: id,
					sort: sort
				}, this.apiPath1).then(response => {
					this.$message({
						message: '排序成功',
						type: 'success'
					})
				})
			},
			//启用
			handleShow1(id = 0) {
				this.$confirm('确认启用数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$api.show({ id_str: id }, this.apiPath1).then(response => {
						// 重新获取列表
						this.getItemList()
						this.$message({
							message: '启用成功',
							type: 'success'
						})
					})
				})
			},
			//禁用
			handleUpshow1(id = 0) {
				this.$confirm('确认禁用数据吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$api.upshow({ id_str: id }, this.apiPath1).then(response => {
						// 重新获取列表
						this.getItemList()
						this.$message({
							message: '禁用成功',
							type: 'success'
						})
					})
				})
			}
/*******************************公共方法1END******************************/
		}
	}
</script>
